package com.youfang.sixthmedia.ui.detail;

import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.Html;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.gzit.adapter.CustomerListAdapter;
import com.gzit.common.async.AsynCallback;
import com.gzit.utils.AndroidUtils;
import com.gzit.utils.DateUtil;
import com.youfang.sixthmedia.R;
import com.youfang.sixthmedia.common.YoufangContext;
import com.youfang.sixthmedia.controller.PhotoController;
import com.youfang.sixthmedia.message.collect.AddToCollectListRequest;
import com.youfang.sixthmedia.message.collect.AddToCollectListResponse;
import com.youfang.sixthmedia.message.collect.RemoveFromCollectRequest;
import com.youfang.sixthmedia.message.collect.RemoveFromCollectResponse;
import com.youfang.sixthmedia.message.groupon.AddGrouponRequest;
import com.youfang.sixthmedia.message.groupon.AddGrouponResponse;
import com.youfang.sixthmedia.message.groupon.CancelGrouponRequest;
import com.youfang.sixthmedia.message.groupon.CancelGrouponResponse;
import com.youfang.sixthmedia.message.model.DetailBuilding;
import com.youfang.sixthmedia.message.model.DetailBuilding.PhotoItem;
import com.youfang.sixthmedia.net.Net;
import com.youfang.sixthmedia.net.Response;
import com.youfang.sixthmedia.ui.weibo.ShareSinaWeiboActivity;
import com.youfang.sixthmedia.ui.weibo.ShareTencentWeiboActivity;

public class DetailBuildingActivity extends Activity {

	private PhotoController controller = new PhotoController();
	private PhotoAdapter photoAdapter;

	class PhotoAdapter extends CustomerListAdapter<PhotoItem> {

		public PhotoAdapter(Context context) {
			super(context, R.layout.building_photo_item);
		}

		@Override
		protected void render(PhotoItem item, View view) {

			ImageView photo = (ImageView) view.findViewById(R.id.photo);
			if ((!YoufangContext.showPic) || item.localURI == null) {
				photo.setImageResource(R.drawable.nophoto);
				return;
			}

			photo.setImageURI(item.localURI);

		}

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AndroidUtils.Screen.noWindowTitle(this);
		this.setContentView(R.layout.detail_building_activity);

		Gallery gallery = (Gallery) this.findViewById(R.id.gallery);
		photoAdapter = new PhotoAdapter(this);
		gallery.setAdapter(photoAdapter);
		controller.setup(gallery, photoAdapter);

		final DetailBuilding detail = YoufangContext.getCurrentBuilding();

		if (detail != null) {

			this.updateUI();

			OnClickListener listener = new OnClickListener() {

				@Override
				public void onClick(View v) {

					switch (v.getId()) {
					case R.id.address_container:
						gotoBuildingLocationActivity(detail);
						break;

					case R.id.favbtn:
						remoteFav(detail);

						break;
					case R.id.groupbtn:
						remoteGroupOn(detail);

						break;
					case R.id.weibobtn:
						showShareMenu();
						break;
					}

				}
			};

			// 点击地址栏打开楼盘的位置
			this.findViewById(R.id.address_container).setOnClickListener(
					listener);

			// collect or groupon
			this.findViewById(R.id.favbtn).setOnClickListener(listener);
			this.findViewById(R.id.groupbtn).setOnClickListener(listener);

			// share
			this.findViewById(R.id.weibobtn).setOnClickListener(listener);

		}

		initMenu();

	}

	ViewFlipper menuFlipper;
	PopupWindow popupSave;
	View menuLayout;

	private void initMenu() {
		menuFlipper = new ViewFlipper(this);
		menuFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
				R.anim.menu_in));
		menuFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
				R.anim.menu_out));
		menuFlipper.setFlipInterval(600000);
		menuLayout = this.getLayoutInflater().inflate(
				R.layout.share_weibo_menu, null);
		menuFlipper.addView(menuLayout);
		// tvSave = (TextView) menuLocalSaveLayout.findViewById(R.id.save);
		// tvCancel = (TextView) menuLocalSaveLayout.findViewById(R.id.cancel);
		popupSave = new PopupWindow(menuFlipper, LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT);
		popupSave.setFocusable(true);
		popupSave.setBackgroundDrawable(new BitmapDrawable());
		popupSave.update();

		OnClickListener listener = new OnClickListener() {

			@Override
			public void onClick(View v) {
				popupSave.dismiss();
				Intent intent = new Intent();
				switch (v.getId()) {
				case R.id.sina_weibo_btn:
					intent.setClass(DetailBuildingActivity.this,
							ShareSinaWeiboActivity.class);
					startActivity(intent);

					break;
				case R.id.qq_weibo_btn:
					// share content to tencent weibo
					intent.setClass(DetailBuildingActivity.this,
							ShareTencentWeiboActivity.class);
					startActivity(intent);

					break;
				case R.id.renren_weibo_btn:
					break;
				case R.id.cancel_weibo_btn:
					break;

				}

			}
		};

		for (int id : new int[] { R.id.sina_weibo_btn, R.id.qq_weibo_btn,
				R.id.renren_weibo_btn, R.id.cancel_weibo_btn }) {
			menuLayout.findViewById(id).setOnClickListener(listener);

		}

	}

	public static void setLayoutAlpha(Activity activity, float alpha) {
		WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
		lp.alpha = alpha; // 0.0-1.0
		activity.getWindow().setAttributes(lp);
	}

	private void showShareMenu() {

		if (popupSave != null) {
			if (popupSave.isShowing()) {
				popupSave.dismiss();
			} else {
				setLayoutAlpha(this, 0.5f);
				popupSave.showAtLocation(this.findViewById(R.id.weibobtn),
						Gravity.BOTTOM, 0, 0);
				menuFlipper.startFlipping();// 播放动画
			}
		}

	}

	private void remoteFav(final DetailBuilding detail) {
		if (detail == null) {
			return;
		}

		if (!YoufangContext.isLogined()) {

			// goto login activity... after login we should refresh the
			// detailbuilding status(wheather it is collected? do it
			// onactivityresult
			Net.gotoLoginActivity(this);
			return;
		}

		// not collected ,do collect action...
		if (!detail.isCollected()) {
			AddToCollectListRequest req = new AddToCollectListRequest();
			req.setHouseid(detail.id);
			Net.doHttpRemote(this, req, new AddToCollectListResponse(),
					new AsynCallback<Response>() {

						@Override
						public void callback(Response r) {
							if (!r.isOk()) {
								AndroidUtils.toastShort("收藏失败");
								return;

							}
							detail.iscollect = DetailBuilding.COLLECTED;
							((Button) findViewById(R.id.favbtn))
									.setText("取消收藏");
							AndroidUtils.toastShort("收藏成功");

						}
					});

			return;
		}

		// collected,do cancel collect action...
		RemoveFromCollectRequest req = new RemoveFromCollectRequest();
		req.setHouseid(detail.id);
		Net.doHttpRemote(this, req, new RemoveFromCollectResponse(),
				new AsynCallback<Response>() {

					@Override
					public void callback(Response r) {
						if (!r.isOk()) {
							AndroidUtils.toastShort("取消收藏失败");
							return;
						}

						detail.iscollect = DetailBuilding.NOT_COLLECTED;
						((Button) findViewById(R.id.favbtn)).setText("收藏楼盘");
						AndroidUtils.toastShort("取消收藏成功");

					}
				});

	}

	private void remoteGroupOn(final DetailBuilding detail) {
		if (detail == null) {
			return;
		}

		if (!YoufangContext.isLogined()) {
			Net.gotoLoginActivity(this);
			return;

		}

		if (!detail.isGroupOned()) {
			AddGrouponRequest req = new AddGrouponRequest();
			req.setHouseid(detail.id);
			Net.doHttpRemote(this, req, new AddGrouponResponse(),
					new AsynCallback<Response>() {

						@Override
						public void callback(Response r) {
							if (!r.isOk()) {
								AndroidUtils.toastShort("参与团购失败");
								return;
							}

							detail.isgroupon = DetailBuilding.GROUPONED;
							((Button) findViewById(R.id.groupbtn))
									.setText("取消团购");
							AndroidUtils.toastShort("团购成功");

						}
					});

			return;

		}

		// remote cancel groupon...
		CancelGrouponRequest req = new CancelGrouponRequest();
		req.setHouseid(detail.id);
		Net.doHttpRemote(this, req, new CancelGrouponResponse(),
				new AsynCallback<Response>() {

					@Override
					public void callback(Response r) {
						if (!r.isOk()) {
							AndroidUtils.toastShort("取消团购失败");
							return;
						}

						detail.isgroupon = DetailBuilding.NOT_GROUPONED;
						((Button) findViewById(R.id.groupbtn)).setText("参与团购");
						AndroidUtils.toastShort("取消团购成功");

					}
				});

	}

	private void gotoBuildingLocationActivity(DetailBuilding detail) {
		Intent intent = new Intent();
		intent.setClass(this, DetailLocationActivity.class);
		intent.putExtra("detail", detail);
		this.startActivity(intent);

	}

	public void updateUI() {

		DetailBuilding detail = YoufangContext.getCurrentBuilding();

		TextView buildingname = (TextView) this.findViewById(R.id.buildingname);
		buildingname.setText(detail.buildingname);

		TextView buildingnameTitle = (TextView) this
				.findViewById(R.id.buildingname_title);
		buildingnameTitle.setText(detail.buildingname);

		TextView price = (TextView) this.findViewById(R.id.price);
		price.setText("0".equals(detail.price) ? "价格待定" : detail.price + "元/㎡");

		TextView opentime = (TextView) this.findViewById(R.id.opentime);
		opentime.setText("0".equals(detail.opentime) ? "待定" : DateUtil
				.date2String(new Date(detail.opentime)));

		TextView readnum = (TextView) this.findViewById(R.id.readnum);
		readnum.setText(detail.readnum);

		TextView region = (TextView) this.findViewById(R.id.region);
		region.setText(detail.region);

		TextView buildingtype = (TextView) this.findViewById(R.id.buildingtype);
		buildingtype.setText(detail.buildingtype);

		TextView address = (TextView) this.findViewById(R.id.address);
		address.setText(detail.address);

		TextView dev = (TextView) this.findViewById(R.id.dev);
		dev.setText(detail.dev);

		TextView special = (TextView) this.findViewById(R.id.special);
		special.setText(detail.special);

		TextView surroundbusi = (TextView) this.findViewById(R.id.surroundbusi);
		surroundbusi.setText(Html.fromHtml(detail.surroundbusi));

		TextView surroundtraffic = (TextView) this
				.findViewById(R.id.surroundtraffic);
		surroundtraffic.setText(Html.fromHtml(detail.Surroundtraffic));

		// set the label of button according to collect flag and gourpon flag;
		((Button) this.findViewById(R.id.favbtn))
				.setText(detail.isCollected() ? "取消收藏" : "收藏楼盘");
		((Button) this.findViewById(R.id.groupbtn)).setText(detail
				.isGroupOned() ? "取消团购" : "参与团购");

		photoAdapter.reload(detail.items);
		controller.onRefresh(detail.items);

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode != Activity.RESULT_OK) {
			return;
		}

		switch (requestCode) {
		case Net.LOGIN_REQUEST_CODE:

			// reload building info after login.
			((TabDetailBuildingActivity) this.getParent())
					.remoteLoadBuildingDetail(new AsynCallback<Response>() {

						@Override
						public void callback(Response r) {
							updateUI();

						}
					});
			break;
		}

	}
}
